import { Crypto } from './crypto-min.js'
import { Base64 } from "./js-base64/base64"
import LocalStorage from "../utils/storage"
const BASE_UPLOAD = "https://global-application-001.downline.cn"

const policyText = {
  'expiration': '2099-01-01T12:00:00.000Z', // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
  'conditions': [['content-length-range', 0, 1048576000] // 设置上传文件的大小限制
  ]
}


/** 生成随机文件名 格式为随机6位数+时间戳+文件类型 */
function getFileName(filename) {
  const pos = filename.lastIndexOf('.')
  // console.log(pos)
  if (pos !== -1) {
    return randomString(6) + new Date().getTime() + filename.substring(pos - 1)
  }
  return ''
}

/** 随机数 未指定长度则为32位 */
function randomString(len) {
  len = len || 32
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  const maxPos = chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
const setAndGetOssParams = () => {
  if (!LocalStorage.read('ossParams')) {
    const res = {
      oss_host_url: 'https://global-application-001.downline.cn',
      app_main_url: 'casekadingche.downline.cn',
      oss_accesskey: 'hgV5TOnVHZWvXYV98QMqm1Avt7Q3mD',
      oss_accessid: 'scj0YOTsBy74ZWGy'
    }
    const ossParams = {
      key: res['app_main_url'] + '/goods_image/',
      accesskey: res['oss_accesskey'],
      OSSAccessKeyId: res['oss_accessid']
    }
    LocalStorage.set('ossParams', Base64.encode(JSON.stringify(ossParams)))
  }
  return LocalStorage.read('ossParams');
}

export function upload(data, file) {
  data = JSON.parse(Base64.decode(setAndGetOssParams()));
  const policyBase64 = Base64.encode(JSON.stringify(policyText))
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, data.accesskey, { asBytes: true })
  const signature = Crypto.util.bytesToBase64(bytes)
  return new Promise((resolve,reject)=>{
    let key=`${data.key + getFileName(file)}`;
    wx.uploadFile({
      url: `${BASE_UPLOAD}`,
      filePath: file,
      name: 'file',
      formData: {
        'key': key,
        'policy': policyBase64,
        'success_action_status': 200,
        'OSSAccessKeyId': data.OSSAccessKeyId,
        'signature': signature,
        'file': file.raw
      },
      header:{
        'Accept': 'application/json, text/javascript, */*; q=0.01' 
      },
      success:(res)=>{
        resolve(`${BASE_UPLOAD}/${key}`)
      },
      fail:(error)=>{
        // console.log(error,">>>upload")
        resolve("")
      }
    })
  })


  // return axios.post('https://global-application-001.downline.cn', multipart_params, config).then(() => {
  //   return 'https://global-application-001.downline.cn/' + multipart_params.get('key')
  // })

  // return http.post('https://global-application-001.downline.cn', multipart_params, config).then(() => {
  //     return process.env.VUE_APP_OSS_URL + '/' + multipart_params.get('key')
  // })
}